package com.xuanyang.dormrepair.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanyang.dormrepair.config.ServiceException;
import com.xuanyang.dormrepair.model.entity.User;
import com.xuanyang.dormrepair.model.mapper.UserMapper;
import com.xuanyang.dormrepair.utils.JwtKit;
import com.xuanyang.dormrepair.utils.PageKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @AUTHOR soft
 * @DATE 2019/5/19 1:48
 * @DESCRIBE
 */
@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 管理员用户登录
     * @param user 管理员用户信息
     */
    public User login(User user) {
        User u = byUsername(user.getUsername());
        if (u == null) throw new ServiceException("用户名不存在！");

        String md5 = JwtKit.md5(user.getUsername(), user.getPassword());
        if (!u.getPassword().equals(md5)) throw new ServiceException("密码错误！");

        return u;
    }

    @Transactional
    public boolean add(User user) {
        user.setPassword(JwtKit.md5(user.getUsername(), user.getPassword()));
        return userMapper.insert(user) > 0;
    }

    @Transactional
    public boolean delete(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Transactional
    public boolean update(User user) {
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(JwtKit.md5(user.getUsername(), user.getPassword()));
        }

        return userMapper.updateById(user) > 0;
    }

    public User byUsername(String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }

    public User byId(Integer id) {
        return userMapper.selectById(id);
    }

    public IPage<User> page(int page, int limit, User query) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(query);

        return userMapper.selectPage(PageKit.of(page, limit), wrapper);
    }
}
